package com.ld.tool.window;

import com.alibaba.fastjson.JSONObject;
import com.ld.translate.TranslateFactory;
import com.ld.utils.CommonUtils;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

public class TranslatePanel {
    public JRadioButton en;
    public JTextArea context;
    public JButton translate;
    public JTextArea result;
    public JPanel root;
    private JRadioButton auto;
    private JRadioButton ch;
    private JButton copyOriginal;
    private JButton copySmallHump;
    private JButton copyBigHump;
    private JButton copyUnderline;
    private JButton clear;

    public JPanel getRoot() {
        ButtonGroup btnGroup = new ButtonGroup();
        btnGroup.add(auto);
        btnGroup.add(ch);
        btnGroup.add(en);
        translate.addActionListener(e -> {
            startTranslate();
        });
        context.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                System.out.println("insertUpdate");
                automaticTranslation();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                System.out.println("removeUpdate");
                automaticTranslation();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                automaticTranslation();
            }
        });
        copyOriginal.addActionListener(e -> {
            copy(result.getText(),0);
        });
        copySmallHump.addActionListener(e -> {
            copy(result.getText(),1);
        });
        copyBigHump.addActionListener(e -> {
            copy(result.getText(),2);
        });
        copyUnderline.addActionListener(e -> {
            copy(result.getText(),3);
        });
        clear.addActionListener(e->{
            context.setText("");
            result.setText("");
        });
        return root;
    }

    static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    static ScheduledFuture<?> scheduledFuture;

    public void automaticTranslation(){
        if (scheduledFuture != null && !scheduledFuture.isDone()){
            boolean cancel = scheduledFuture.cancel(true);
            System.out.println(cancel);
        }
        scheduledFuture = scheduledExecutorService.schedule(() -> {
            startTranslate();
        }, 1, TimeUnit.SECONDS);
    }

    public void startTranslate(){
        String type = "";
        String contextText = context.getText();
        if (auto.isSelected()){
            type = explanation(contextText);
        }else if (ch.isSelected()){
            type = "zh";
        }else if (en.isSelected()){
            type = "en";
        }
        result.setText("Loading...");
        String t = type;
        CommonUtils.run(()->{
            System.out.println("contextText:"+contextText);
            String google = "";
            switch (t){
                case "zh":
                    google = translation(contextText,"zh","en");
                    break;
                case "en":
                    google = translation(contextText, "en","zh");
                    break;
                default:
                    break;
            }
            System.out.println("google:"+google);
            result.setText(google);
        });
    }

    public void copy(String googleText,int type){
        if (type == 0){
            setSysClipboardText(googleText);
        }else {
            setSysClipboardText(splice(googleText, type));
        }
    }

    public String splice(String googleText,int type){
        String[] split = googleText.split(" ");
        StringBuilder sb = new StringBuilder();
        for (int i = 0,size = split.length; i < size; i++) {
            if (type == 1){
                if (i == 0){
                    sb.append(split[i].toLowerCase());
                }else {
                    String s = split[i];
                    sb.append(s.substring(0, 1).toUpperCase() + s.substring(1));
                }
            }else if (type == 2){
                String s = split[i];
                sb.append(s.substring(0, 1).toUpperCase() + s.substring(1));
            }else if (type == 3){
                sb.append(split[i].toLowerCase());
                if (i+1 != size){
                    sb.append("_");
                }
            }
        }
        return sb.toString();
    }

    public String translation(String context,String a,String b){
        try {
            JSONObject translate = TranslateFactory.getInstance().translate(context, a, b);
            if (translate.getInteger("code") == 200){
                return translate.getString("data");
            }
            return context;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("翻译失败:"+e.getMessage());
            return context;
        }
    }
    private static List<String> skipCharacters = Arrays.asList(",","_","-",".","=");

    private String explanation(String selectedText){
        if (selectedText != null && selectedText.trim().length() > 0){
            int zh = 0;
            int en = 0;
            int length = selectedText.length();
            for (int i = 0; i < length; i++) {
                String trim = String.valueOf(selectedText.charAt(i)).trim();
                if (trim.length() == 0 || skipCharacters.contains(trim)){
                    continue;
                }
                Pattern pattern = Pattern.compile("[a-zA-Z]");
                if (pattern.matcher(trim).matches()){
                    ++en;
                }else {
                    zh+=3;
                }
            }
            if (zh > en){
                return "zh";
            }else {
                return "en";
            }
        }else {
            return "zh";
        }
    }

    public void setSysClipboardText(String writeMe) {
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable tText = new StringSelection(writeMe);
        clip.setContents(tText, null);
    }
}
